package com.store.app.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.store.app.ExitApplication;
import com.store.app.LocationApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.bean.CouponUpdateBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.UserTokenUtils;
import com.store.app.utils.Utils;
import com.store.app.zxing.Capture_ZxingActivity;

import net.sourceforge.zbar.ImageScanner;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;

import de.greenrobot.event.EventBus;

/**
 * 免费领扫一扫
 */
public class FreeScanActivity extends Capture_ZxingActivity implements IOnHttpListener, OnClickListener {

    private static String cardNo;//卡号
    private RelativeLayout ryScanResult;
    private TextView tvCardCode;
    private TextView tvCardStatus;
    private static final int MSG_REQUEST_SUCCESS = 0;
    private static final int MSG_REQUEST_FAILED = 1;
    private static final int MSG_QUERY_FAMILY_CARD_SUCCESS = 2;//成功
    private static final int MSG_QUERY_FAMILY_CARD_FAIL = 3;//失败（亲情卡已激活）
    private static final int MSG_RESTART_SCAN = 4;//重新开启扫描
    private Handler mHandler;
    private ImageScanner mImageScanner = null;
    private TextView tv_cap;
    private String cardState;
    private String cardStateInfo;
    private NetRequest netRequest;
    private RelativeLayout rl_dialog_fail;      //失败弹窗
    private RelativeLayout rl_dialog_success;   //成功弹窗
    private TextView tv_fail_ok;
    private TextView tv_success_ok;
    private TextView tv_dialog_success_content;
    private Dialog mDownloadDialog;

    private String goods_code ;
    private String goods_url ;
    private String amount ;

    private String mthCardNo;//扫描得到的亲情卡号
    @Override
    public void onAfinalFail() {
        rl_dialog_success.setVisibility(View.GONE);
        rl_dialog_fail.setVisibility(View.GONE);
        mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 5000);
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            try {
                JSONObject data = new JSONObject(result);
                String member_id = data.getString("member_id");
                Log.v("zyl", "获取到的member_id为：" + member_id);
                netRequest.requestFreeGet(3, goods_code, goods_url, amount, member_id, mthCardNo);
                mthCardNo = "";
            }catch (Exception e){}
        }else if(requestId == 2 ){
            try {
                JSONObject jsonObject = new JSONObject(result);
                String member_id = jsonObject.getString("member_id");
                Log.v("zyl", "获取到的member_id为2：" + member_id);
                netRequest.requestFreeGet(3, goods_code, goods_url, amount, member_id, mthCardNo);
                mthCardNo = "";
            }catch (Exception e){}
//            showToast("已发送短信！");
        }else if(requestId ==3){
            showToast("已发送短信!");
            finish();
        }
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 5000);
            showToast(msg);
    }

    private void initView() {
        Intent intent = getIntent();
        if(intent!=null){
            goods_code = intent.getStringExtra("goods_code");
            goods_url = intent.getStringExtra("goods_url");
            amount = intent.getStringExtra("amount");
        }
        rl_dialog_fail = (RelativeLayout) findViewById(R.id.rl_dialog_fail);
        rl_dialog_success = (RelativeLayout) findViewById(R.id.rl_dialog_success);
        tv_fail_ok = (TextView) findViewById(R.id.tv_fail_ok);
        tv_fail_ok.setOnClickListener(this);
        tv_success_ok = (TextView) findViewById(R.id.tv_success_ok);
        tv_success_ok.setOnClickListener(this);
        tv_dialog_success_content = (TextView) findViewById(R.id.tv_dialog_success_content);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_fail_ok:
                rl_dialog_fail.setVisibility(View.GONE);
                break;
            case R.id.tv_success_ok:
                rl_dialog_success.setVisibility(View.GONE);
                break;
        }
    }

    private class WeakHandler extends Handler {
        private final WeakReference<FreeScanActivity> mReference;

        public WeakHandler(FreeScanActivity activity) {
            mReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            FreeScanActivity activity = mReference.get();
            if (activity == null) {
                return;
            }
            activity.dismissProgressDialog();
            switch (msg.what) {

                case MSG_QUERY_FAMILY_CARD_SUCCESS:
                    break;
                case MSG_QUERY_FAMILY_CARD_FAIL:
//					Toast.makeText(ValidateCouponActivity.this,cardStateInfo,Toast.LENGTH_LONG).show();
                    break;
                case MSG_RESTART_SCAN:
                    Log.v("zyl", "重新开启扫描");
                    setReCapture();
                    break;
                default:
                    break;
            }
        }
    }


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_free_scan);
        initView();
        getWindow()
                .addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setInintView();
        initData();
        mHandler = new WeakHandler(this);
        findViewById();
    }

    private void initData() {
        UserTokenUtils.setUerToken(this);
        netRequest = new NetRequest(this);
    }

    private void findViewById() {
        findViewById(R.id.retreat).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_cap = (TextView) findViewById(R.id.cap_tv);
        int width = LocationApplication.app.getDM().widthPixels;
        int high=LocationApplication.app.getDM().heightPixels;
        width = width / 8 * 3;
        high = high / 2 + width;
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.topMargin = high + MainActivity.dip2px(20);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        tv_cap.setLayoutParams(layoutParams);
        tv_cap.setText("扫描会员二维码或亲情卡");
    }


    /**
     * 处理扫描结果
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        Log.v("zyl", "resultString:" + resultString);

        if (TextUtils.isEmpty(resultString)) {
            Toast.makeText(FreeScanActivity.this, "扫描错误!", Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 5000);
        } else {
                    mthCardNo ="";
                if (resultString.length() > 3) {
                    String identifying = resultString.substring(0, 3);
                    if (identifying.equals("MTH")) {
//                        String sktCode = resultString.substring(3, resultString.length());
                        netRequest.requestCardScan(1, resultString);
//                        netRequest.requestCouponValidate(1, sktCode);
                        Log.v("zyl", "YHQ---SKTCODE:" + resultString);
                        mthCardNo = resultString;
//                        mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 3000);
                    } else {
                        if(Utils.matchPhone(resultString)){
                            mthCardNo="";
                            Log.v("zyl","正常手机号");
                            netRequest.requestQueryConsumerMememberId(2, resultString);
                        }else{
                            mHandler.sendEmptyMessageDelayed(MSG_RESTART_SCAN, 5000);
                            Toast.makeText(FreeScanActivity.this, "请展示亲情卡或者消费者二维码！", Toast.LENGTH_SHORT).show();
                            Log.v("zyl","非正常手机号");
                            return;
                        }
//                        Toast.makeText(FreeScanActivity.this, "不支持扫描该条码！", Toast.LENGTH_SHORT).show();
                    }
                }
                cardNo = resultString;
            }

    }


    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
